package com.xian.im.modules.command.group.handler;

import com.xian.im.common.constant.CommandCodeConstant;
import com.xian.im.common.exception.BusinessException;
import com.xian.im.common.model.dto.GroupDto;
import com.xian.im.common.model.session.SessionUser;
import com.xian.im.common.proto.MsgRequest;
import com.xian.im.common.proto.MsgResponse;
import com.xian.im.common.utils.bussiness.XimResponseUtil;
import com.xian.im.common.utils.sys.SpringContextHolder;
import com.xian.im.modules.avchat.manager.ImGroupManager;
import com.xian.im.modules.command.group.AbsGroupCommand;
import com.xian.im.modules.message.GroupHandler;

import java.util.Set;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-01-28 22:38
 **/
public class GroupKick extends AbsGroupCommand {

    @Override
    public void handler(MsgRequest request, String ctx, GroupDto groupEntity) {
        SessionUser session = userChannelClient().session(ctx);
        if (session.getAccount().equals(request.getToAccount())) {
            throw new BusinessException("不能踢出自己");
        }
        String toAccount = request.getToAccount();
        String groupUniqueId = request.getGroupUniqueId();
        Set<String> ctxIds = userChannelClient().ctxIds(toAccount);
        String name = "";

        for (String ctxId : ctxIds) {
            groupChannelClient().kick(ctxId,groupUniqueId);
            SessionUser param = userChannelClient().session(ctx);
            name = param.getNickname();
        }

        MsgResponse response = XimResponseUtil.buildSuccess(session);
        response.setGroupUniqueId(groupEntity.getGroupUniqueId());
        response.setBody("管理员" + response.getUser().getNickname() + ",将" + name + "踢出了房间");
        GroupHandler.groupSendAll(response, request.getGroupUniqueId());
    }

    /**
     * 群组code
     *
     * @return
     */
    @Override
    public String cmdCode() {
        return CommandCodeConstant.GROUP_KICK;
    }

    private static ImGroupManager groupManager(){
        return SpringContextHolder.getBean(ImGroupManager.class);
    }
}
